
import express, { Request, Response } from "express"
import homeRouter from "./home"
import { AccountContext } from "../../context/AccountContext"
import { LoginParam } from "@Tea/model"
import { AppToken } from "../../dao/AppToken"
import { checkAppToken, checkError } from "../../utils/token"
import orderRouter from "./order"
import shoppingCarRouter from "./shoppingCar"
import mineRouter from "./mine"
import locationRouter from "./location"
import searchRouter from "./search"
import { useCheckAndResponse } from "../../utils/common"

const appRouter = express.Router()

appRouter.use('/home', homeRouter)
appRouter.use('/order', checkAppToken, orderRouter)
appRouter.use('/shoppingCar', checkAppToken, shoppingCarRouter)
appRouter.use('/mine', checkAppToken, mineRouter)
appRouter.use('/mine/location', checkAppToken, locationRouter)
appRouter.use('/search', searchRouter)

appRouter.post("/login", async (req: Request, res: Response) => {
  const loginParam = req.body as LoginParam
  try {
    const accoutCxt = AccountContext.getInstance()

    const data = (await accoutCxt.verify(loginParam))[0][0]

    if (data) {
      if (!data.enable) {
        res.send({
          code: 0,
          msg: "账号被禁用",
        })

        return
      }
      console.log(data);

      const token = AppToken.getInstance()
      const TokenObject = token.refreshToken(data.userId)

      res.cookie(`tea_online`, TokenObject.token)

      res.send({
        code: 1,
        data: data,
      })

    } else {
      res.send({
        code: 0,
        msg: "账号未注册"
      })
    }
  } catch (e) {
    res.status(500).send({
      code: 0,
      msg: checkError(e)
    })
  }
})

appRouter.delete("/loginOut", checkAppToken, async (req: Request, res: Response) => {
  try {
    const accoutCxt = AccountContext.getInstance()
    const result = accoutCxt.loginOut(req.cookies['tea_online'])

    if (result) {
      res.send({
        code: 1,
        msg: "退出登录成功"
      })
    } else {
      res.status(401).send({
        code: 0,
        msg: "未发现登录信息"
      })
    }

  } catch (e) {
    res.status(500).send({
      code: 0,
      msg: checkError(e)
    })
  }
})



appRouter.post("/register", async (req: Request, res: Response) => {
  const { account, username, password } = req.body

  try {
    // 查账号
    const checkRes = await AccountContext.getInstance().checkAccount(account)

    // 如果有账号，返回错误提示
    if (checkRes[0]) {
      res.send({
        code: 0,
        msg: "账号已存在"
      })
    } else {
      const registerRes = await AccountContext.getInstance().register(account, username, password)

      useCheckAndResponse(res, registerRes[0], '注册成功')
    }
  } catch (e) {
    res.status(500).send({
      code: 0,
      msg: checkError(e)
    })
  }
})


export default appRouter